<template>
    <div class="for-cover looking">
        <no-data v-if="storeMsg && Object.keys(storeMsg).length > 0 && storeMsg.list && storeMsg.list.length == 0">
        </no-data>
        <!--:rtCommontListProps="rtCommontListProps"-->
        <full-img-video-swiper
            v-else-if="storeMsg && Object.keys(storeMsg).length > 0 && storeMsg.list && storeMsg.list.length > 0"
            :swiperContentProp="storeMsg" :commentListProps="commentListProps" :rtCommontListProps="shareCollectSpeak"
            @isLike="isLike" @doComment="doComment" @showShare="showShare = true" @getSubCommentList="getSubCommentList"
            @swiperSlideEnd="swiperSlideEnd" @getUserMainComment="getUserMainComment" @isShowHomeTap="isShowHomeTap"
            @lastSlide="nextSwiperSlide" @clickHeaderImg="toUserInfo" @doAttention="doAttention">
        </full-img-video-swiper>
        <!--分享-->
        <!--互动-->
        <!--<v-themes-->
        <!--v-if="interactProp[key] && pageMsg.interactModel && interactProp[key].interactId == pageMsg.interactModel.interactId"-->
        <!--@recordList="recordList"-->
        <!--:interactProp="interactProp[key]"></v-themes>-->
        <v-share v-if="showShare" @clickFn="showShare = false"></v-share>
    </div>
</template>

<script>
import XLocation from '../../x/XLocation'
import FullImgVideoSwiper from "../../components/commonActModel/panoramaVideoSwiper/FullImgVideoSwiper";

export default {
    name: "Look",
    props: {
        propsPage: {
            type: Object
        }
    },
    data () {
        return {
            bottomText: '下载APP观看更多精彩内容',
            storeMsg: {},
            showAlreadyText: false,//已关注的字样的动画
            curPage: 1,//当前评论页码
            tempIndex: 0,//页面中调用方法的时候太多次数，用一个参数来限制调取的次数
            pageNum: 5,//每次拉取媒体的条数
            shareInfo: [],//分享信息
            commentPageSize: 5,//每次拉取评论的条数
            commentPageNum: 1,//评论的初始页数
            commentListProps: { userHendleType: 'module3' },//评论弹出框的数据
            bordShow: false,//蒙版
            showShare: false,//分享蒙版的显示隐藏
            queryType: 1,//0:默认,1:推荐,2:关注,3:自己,4:喜欢
            swiperIndex: 0,
            swiperTimerout: null,//每次swiper切换之后swiperTimeout都先清除
            interactProp: [],//互动的信息存放
            FHSwiperMsg: {},
            showRecordList: false,//话题的列表
            tabMsg: {},//话题列表信息
            videoMsg: {},
            shareCollectSpeak: [],
            commentList: {
                curPage: 1,
                pageSize: 10
            },
            subCommentList: {
                curPage: 1,
                pageSize: 10
            },
            ids: {
                mediaId: 0,
                mainId: 0,
                subId: 0,
            },
            isCommentSuccess: false,
            discountList: [],
            isShowDiscout: false,
            geolocation: null,
            userLat: 0,
            userLng: 0,
            bottomDownShow: true,
            commentType: 0,
            commentKey: 0,
            wrapSwiperOption: {
                direction: 'vertical',
                speed: 500,
                autoplayDisableOnInteraction: true,
                fade: {/*配合onTransitionEnd解决滑动之后有时不触发slide结束的bug*/
                    crossFade: true,
                },
                onInit: function (swiper) {
                    setTimeout(() => {
                        this.swiperSlideEnd(swiper.activeIndex, true);
                    }, 600)
                }.bind(this),
                onSlideChangeStart () {
                    $("video").each(function (index, ele) {
                        $('video').eq(index)[0].pause();
                    });
                },
                onTransitionEnd: function (swiper) {
                    let that = this;
                    this.swiperIndex = swiper.activeIndex;
                    this.swiperSlideEnd(swiper.activeIndex);
                    if (swiper.activeIndex == this.pageNum - 1) {
                        this.openHKHWConfirm('查看更多需要下载【好看好玩】');
                    }
                }.bind(this),
            },
        }
    },
    created () {

    },
    mounted () {
        let that = this;
        let keys = that.propsPage ? Object.keys(that.propsPage) : {};
        if (this.propsPage && keys.includes("bottomDownShow")) {
            this.bottomDownShow = this.propsPage.bottomDownShow;
        }
        this.init();
        this.$store.commit('getqueryType', that.queryType)
    },
    methods: {
        init () {
            this.getLookMsg();
            // this.videoAutoplay();
        },
        mediaCommentText (index) {
            let screenWidth = document.documentElement.clientWidth;
            let isShow = screenWidth / 375 * $('.media-comment-text').eq(index).width() / 100 > 3.05;
            return isShow;
        },
        getLookMsg () {
            let that = this;
            if (this.propsPage) {
                let item = this.propsPage.showItem;
                switch (item) {
                    case 0: that.queryType = 1; break;
                    case 1: that.queryType = 2; break;
                    case 2: that.queryType = 3; break;
                }
            }
            that.ids.mediaId = this.$route.params.mediaId;
            let userLocation = XLocation.getUserLocation();
            if (!(userLocation && (userLocation.longitude || userLocation.latitude))) {
                userLocation = {
                    longitude: 0,
                    latitude: 0,
                }
            }
            let params = {
                longitude: userLocation.longitude,
                latitude: userLocation.latitude,
            };
            let userLocationUrl = `${that.NW_API_API_LOCALE_VERSION}/location/city`;
            this.xurl.getLoading(userLocationUrl, params).then((req) => {
                if (req.success) {
                    getLookingMsg({ areaId: req.result.areaId });
                } else if (req.errMsg) {
                    // that.$root.$emit('toast', {msg: req.errMsg});
                    console.log('req.errMsg')
                    getLookingMsg();
                } else {
                    // that.$root.$emit('toast', {msg: '定位失败'});
                    console.log('定位失败')
                    getLookingMsg();
                }
            });
            // let url = `${this.NW_API}/media/info/get?mediaId=${that.ids.mediaId }`;
            //获取好看好玩信息
            function getLookingMsg (obj) {
                let paramas = {
                    "userInfo": {
                        "userId": that.userId,                  //----用户id (未登录用户时传null或0)
                        "deviceType": 2,                        //----@设备类型
                        "deviceId": that.getDeviceId(),         //----设备id (必须要准确的唯一标识，不然会出问题)
                        "longitude": userLocation.longitude,                  //----用户当前所在经度
                        "latitude": userLocation.latitude,                    //----用户当前所在纬度
                        "gpsAreaId": obj && obj.areaId ? obj.areaId : 0,      //----地理定位区域id
                        "selectAreaId": obj && obj.areaId ? obj.areaId : 0,   //----app内选定区域id
                    },
                    "queryType": that.queryType,
                    // "userId": that.userId ? that.userId :null,
                    "userId": null,
                    "storeId": null,
                    "itemId": null,
                    "mediaType": null,
                    "keyWord": null,
                    "headMediaId": that.propsPage.showItem == 0 && that.$route.query.shareId ? that.$route.query.shareId : null,
                };
                that.$store.dispatch('getLookingMsgApi', paramas).then((data) => {
                    if (data.success) {
                        let tempObj = { showMoreLine: false };
                        let tempArray = [];
                        let isSelf = {};
                        for (let value in data.list) {
                            isSelf = { isSelf: that.userId == data.list[value].belongUserInfo && data.list[value].belongUserInfo.userId ? data.list[value].belongUserInfo.userId : 0 };
                            data.list[value] = Object.assign({}, data.list[value], tempObj)
                            tempArray.push(Object.assign({}, data.list[value].interactModel, isSelf))
                        }
                        that.interactProp = tempArray;
                        data = Object.assign({}, data, { headerMsg: 'moudule2' });
                        that.storeMsg = data;
                        that.dealShareCollectSpeak(data)
                        // that.dealShareBodyInfo(data);
                    } else if (data.errMsg) {
                        that.$root.$emit('toast', { msg: data.errMsg })
                    } else {
                        that.$root.$emit('toast', { msg: '获取数据出错' })
                    }
                })
            }
        },
        swiperSlideEnd (index, isInit = false) {
            let that = this;
            setTimeout(() => {
                if (this.isIphone) {
                    $("video").each(function (index, ele) {
                        $('video').eq(index)[0].pause();
                    });
                }
                if ($('#mySwiper>.swiper-wrapper>.swiper-slide').eq(index).find('video')) {
                    if (this.isIphone) {
                        setTimeout(() => {
                            for (let value in that.$refs.fullVideo) {
                                if (that.$refs.fullVideo && that.$refs.fullVideo[value] && that.$refs.fullVideo[value].$attrs['data-videoIndex'] == index) {
                                    console.log('playVideo')
                                    that.$refs.fullVideo[value].playVideo();
                                }
                            }
                        })
                    }
                }
                /*这个加在这里的作用是要在播放视频的时候关掉所有swiper*/
                for (let value in that.$refs.fullSwiper) {
                    that.$refs.fullSwiper[value].swiperShow = false;
                    if (that.$refs.fullSwiper[value].$attrs['data-imgIndex'] == index) {
                        that.$refs.fullSwiper[value].swiperShow = true;
                        setTimeout(() => {
                            if (that.$refs.fullSwiper[value].swiperMsg.imagesList.length == 1) {
                                that.nextSwiperSlide(4000);
                            }
                        }, 100)
                    }
                }
            }, 30)

        },
        showPosition (position) {
            if (position) {
                this.userLat = position.lat;
                this.userLng = position.lng;
            }
        },
        showErr () {
            console.log("定位失败")
        },
        /*dealShareBodyInfo*/
        // dealShareBodyInfo (data) {
        //     let url = ''
        //     let that = this;
        //     let tempObj = {};
        //     this.tempIndex++;
        //     data.list.forEach((value, index) => {
        //         url = `${that.NW_API_API_LOCALE_VERSION}/media/info/share/info/get?mediaId=${value.mediaId}&userId=${that.userId}&thirdId=${this.thirdId}&terminalType=6`;
        //         that.xurl.get(url).then((res) => {
        //             if (res.success) {
        //                 tempObj = {
        //                     shareBodyInfo: res.result,
        //                 };
        //                 if (that.storeMsg.list[index]) {
        //                     that.storeMsg.list[index] = Object.assign({}, that.storeMsg.list[index], tempObj);
        //                 }
        //             } else if (data.errMsg) {
        //                 console.log(data.errMsg)
        //             } else {
        //                 console.log('获取分享信息失败')
        //             }
        //         })
        //     });
        // },
        mediaDeal (data) {
            /*mediaContents*/
            if (data.mediaType == 1) {
                let tempObj = {};
                let tempList = [];
                for (let value of data.mediaContents) {
                    tempList.push(value.url);
                }
                tempObj.imagesList = tempList;
                // console.log(tempObj);
                return tempObj;
            } else if (data.mediaType == 0) {
                let videoMsg = {};
                videoMsg.videoUrl = data.mediaContents[0].url;
                videoMsg.poster = data.poster;
                videoMsg.defaultPlayEnd = false;
                return videoMsg;
            }
        },
        dealShareCollectSpeak (data) {
            let tempObj = {};
            let tempArray = [];
            this.shareCollectSpeak = [];
            data.list.forEach((value, index) => {
                tempObj = {
                    isNeedContentShare: false,
                    visitNum: value.dataInfo.visitNum,
                    shareNum: value.dataInfo.shareNum,
                    likeNum: value.dataInfo.likeNum,
                    commentedNum: value.dataInfo.commentedNum,
                    hadLiked: value.queryUserBehaviorInfo.hadLikedMediaInfo,
                    mediaId: value.mediaId,
                    id: value.mediaId,
                };
                tempArray.push(tempObj);
            });
            this.shareCollectSpeak.push(...tempArray);
        },
        getUserMainComment (obj) {
            this.commentPageNum = obj && obj.checkCurPage ? obj.checkCurPage : 1;
            if (obj && obj.mediaId) {
                this.commentKey = obj.mediaId;
            }
            /*commentType 0:多媒体信息 1：店铺实景内容 2：店铺活动 3：店铺商品 4： 商家主页品牌*/
            let params = {
                userId: this.userId,
                commentType: this.commentType,
                commentKey: this.commentKey,
                commentPageNum: this.commentPageNum,
                commentPageSize: this.commentPageSize,

            }
            this.$store.dispatch("getUserMainCommentApi", params).then((data) => {
                if (data.success) {
                    let tempObj = { likeType: 10 };
                    if (obj && obj.isLoadingMore) {
                        /*加载更多*/
                        /*把commentListProps替换掉，里面的list push*/
                        let tempList = this.commentListProps.list;
                        tempList.push(...data.list, ...tempObj);
                        data.list = tempList;
                        this.commentListProps = Object.assign({}, this.commentListProps, data);
                    } else {
                        /*获取第一页*/
                        if (this.commentListProps && !this.commentListProps.children) {
                            this.commentListProps = Object.assign({}, this.commentListProps, data, tempObj);
                        }
                    }
                } else if (data.errMsg) {
                    this.$root.$emit({ msg: data.errMsg })
                } else {
                    this.$root.$emit({ msg: "获取页面信息失败" })
                }
            })
        },
        isShowHomeTap (boolean) {
            this.$emit('isShowHomeTap', boolean);
        },
        getSubCommentList (obj) {
            let that = this;
            let params = {
                mainId: obj.mainId,
                pageNum: obj.pageNum,
                userId: this.userId,
                pageNum: '5',
            }
            this.$store.dispatch('getSubCommentListApi', params).then((data) => {
                if (data.success) {
                    let tempObj = {
                        children: data,
                    };
                    /*把获取到的子评论加人到主评论对像的children里面去*/
                    for (let value in that.commentListProps.list) {
                        if (that.commentListProps.list[value].id == obj.mainId) {
                            if (obj.isMore) {
                                let tempList = that.commentListProps.list[value].children.list;
                                tempList.push(...data.list);
                                tempObj.children.list = tempList;
                                that.commentListProps.list[value] = Object.assign({}, that.commentListProps.list[value], tempObj);
                                that.commentListProps.list.splice(value, 1, that.commentListProps.list[value]);
                            } else {
                                that.commentListProps.list[value] = Object.assign({}, that.commentListProps.list[value], tempObj);
                                that.commentListProps.list.splice(value, 1, that.commentListProps.list[value]);
                            }
                            break;
                        }
                    }
                } else if (data.errMsg) {
                    this.$root.$emit({ msg: data.errMsg })
                } else {
                    this.$root.$emit({ msg: "获取页面信息失败" })
                }
            })
        },
        doAttention (concernType, concernKey, key, cb) {
            if (!this.userId) {
                this.$router.push('/to/login');
                return;
            }
            let that = this;
            let params = {
                likeType: concernType,
                likeKey: concernKey,
                operation: 'do'
            }
            this.$store.dispatch('isLikeApi', params).then((data) => {
                if (data.success) {
                    for (let value in that.storeMsg.list) {
                        if (that.storeMsg.list[value].belongUserInfo.userId == that.storeMsg.list[key].belongUserInfo.userId) {
                            that.storeMsg.list[value].queryUserBehaviorInfo.hadConcernedUser = true;
                            that.storeMsg.list.splice(value, 1, this.storeMsg.list[value]);
                        }
                    }
                    if (cb) {
                        cb();
                    }
                    // this.showAlreadyText = true;
                    // setTimeout(()=>{
                    //     this.showAlreadyText = false
                    // },300);
                } else if (data.errMsg) {
                    this.$root.$emit('toast', { msg: data.errMsg })
                } else {
                    this.$root.$emit('toast', { msg: '关注失败' })
                }
            })
        },
        doComment (obj) {
            let url = '';
            let paramas = {};
            let that = this;
            if (!obj.content || !obj.content.trim()) {
                this.$root.$emit('toast', { msg: "评论内容不能为空！" })
                return;
            }
            /*主评论*/
            if (obj.belongType < 0) {
                paramas = {
                    data: {
                        commentType: that.commentType,
                        commentKey: that.commentKey,
                        content: obj.content
                    },
                    commentLink: 'main'
                }
            } else {
                /*子评论*/
                paramas = {
                    data: {
                        commentMainId: obj.mainId,
                        commentSubId: parseInt(obj.subId) > 0 ? obj.subId : null,
                        content: obj.content
                    },
                    commentLink: 'sub'
                };
            }
            this.$store.dispatch('doCommentApi', paramas).then((data) => {
                if (data.success) {
                    if (obj.belongType < 0) {
                        this.getUserMainComment();
                        /*评论成功之后页面的操作*/
                        if (obj.belongType < 0) {
                            that.storeMsg.list.forEach((value, index, array) => {
                                if (value.mediaId == that.commentKey) {
                                    that.shareCollectSpeak[index].commentedNum++;
                                    that.shareCollectSpeak.splice(index, 1, that.shareCollectSpeak[index]);
                                }
                            })
                        }
                    } else {
                        /*子评论*/
                        obj.pageNum = 1;
                        that.getSubCommentList(obj);
                    }
                    if (obj && obj.cb) {
                        obj.cb();
                    }
                }
            })
        },
        toUserInfo (userId) {
            /*传入被浏览者userId*/
            this.$router.push({ path: '/to/user/info', query: { 'visitId': userId, self: false } });
        },
        nextSwiperSlide (time = 2000) {
            if (this.swiperTimerout) {
                clearTimeout(this.swiperTimerout);
            }
            this.swiperTimerout = setTimeout(() => {
                if (this.$refs.mySwiper.swiper) {
                    this.$refs.mySwiper.swiper.slideNext();
                }
            }, time)
        },
        isLike (obj) {
            // likeType
            ///like/user/{userId}/cancel
            // commentType
            let that = this;
            // http://192.168.1.163:7280/nw_api/api/zh/v1.00/like/user/2004/do?likeType=2&&likeKey=3677
            //http://192.168.1.163:7280/nw_api/api/zh/v1.00/like/user/2004/do?likeType=2&&likeKey=31
            let likeType = -1;
            /*子评论点赞*/
            if (obj && Object.keys(obj).includes('mainkey')) {
                if (Object.keys(obj).includes('subKey')) {
                    likeType = 1;
                } else {
                    likeType = 0;
                }
            } else {
                likeType = 10;
            }
            let operation = obj && obj.isLike ? 'do' : 'cancel'
            let params = {
                userId: this.userId,
                likeKey: obj.likeKey,
                likeType,
                operation,
            }
            this.$store.dispatch('isLikeApi', params).then((data) => {
                if (!data.success) {
                    console.log("点赞失败")
                }
            })
        },
        /*距离*/
        countDistance (storeMsg, key) {
            let that = this;
            if (storeMsg.storeId && storeMsg.storeId != 0 && storeMsg.latitude && storeMsg.longitude && !that.discountList[key]) {
                let tempLocation = XLocation.getLocationDiscount({ latitude: storeMsg.latitude, longitude: storeMsg.longitude });
                tempLocation.then((data) => {
                    let tempObj = {
                        storeId: storeMsg.storeId,
                        discount: data,
                    };
                    that.discountList.splice(key, 1, tempObj);
                });
            }
        },
        deleteComment (deleteMsg) {
            if (!this.userId) {
                this.$router.push('/to/login');
                return
            }
            let url = '';
            let isMain = Object.keys(deleteMsg).length > 0
            if (isMain) {
                let params = {
                    userId: this.$store.state.currentUser.userId,
                    mainId: deleteMsg.mainId
                }
                this.$store.dispatch('deleteCommentApi', params).then((data) => {
                    if (data.success) {
                        if (isMain) {
                            // this.commentListDeal();
                        } else {

                        }
                    } else if (data.errMsg) {
                        that.$root.$emit('toast', { msg: data.errMsg })
                    } else {
                        that.$root.$emit('toast', { msg: '删除失败' })
                    }
                })
            }

        },
        recordList (data) {
            /*TODO 这里没做完，先不往这边拉取数据*/
            return
            this.showRecordList = true;
            setTimeout(() => {
                this.$refs.slideBtm.showSlideBottom();
            }, 100)
        }
    },
    watch: {
        '$route' (to, from) {
            this.$router.go(0);
        },
        userLat: function (val) {
            this.countDistance(this.storeMsg);
        }
    },
    components: {
        "v-share": () => import("../../components/commonComponents/share/Share"),
        "no-data": () => import("../../components/commonActModel/noData/NoData"),
        'v-themes': () => import('../../components/commonActModel/theme/Themes'),
        "full-img-video-swiper": FullImgVideoSwiper,
    }
}
</script>

<style scoped lang="scss">
@import url($css_root+"css/pages/goodLooking/look.css");
.for-cover /deep/ {
    .video-wrap {
        width: 100%;
        overflow: hidden;
    }
    .no-wcomment {
        z-index: 1;
        background-image: linear-gradient(
            rgba(0, 0, 0, 0.3) 0%,
            rgba(0, 0, 0, 0) 20%,
            rgba(0, 0, 0, 0) 80%,
            rgba(0, 0, 0, 0.3) 100%
        );
    }
}
.for-cover {
    background-image: -webkit-linear-gradient(
        rgba(0, 0, 0, 0.3) 0%,
        rgba(0, 0, 0, 0) 20%,
        rgba(0, 0, 0, 0) 80%,
        rgba(0, 0, 0, 0.3) 100%
    );
    background-image: linear-gradient(
        rgba(0, 0, 0, 0.3) 0%,
        rgba(0, 0, 0, 0) 20%,
        rgba(0, 0, 0, 0) 80%,
        rgba(0, 0, 0, 0.3) 100%
    );
    position: relative;
    overflow: hidden;
    height: 100vh;
}
.look-distance {
    top: 0.33rem;
}
</style>